<!--
 * @Author: Z.MingYu
 * @Date: 2025-05-16 15:01:13
 * @Description: 表格标题
-->

<template>
  <table>
    <colgroup>
      <col v-for="col in columns" :key="col.name" :width="col.width" />
    </colgroup>
    <thead ref="thead" v-if="customHeader"></thead>
    <thead v-else>
      <tr>
        <th v-for="col in columns" :key="col.name">{{ col.title }}</th>
      </tr>
    </thead>
  </table>
</template>

<script>
import { isEmpty } from './tableUtils';
export default {
  name: 'ez-table-header',
  props: {
    columns: {
      type: Array[Object],
      default: []
    },
    header: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      customHeader: false
    };
  },
  watch: {
    header: {
      handler(htmlv) {
        if (isEmpty(htmlv)) {
          this.customHeader = false;
        } else {
          this.customHeader = true;
          this.$nextTick(() => {
            const html = this.addRowspanStyle(htmlv);
            if (this.$refs.thead) this.$refs.thead.innerHTML = html;
          });
        }
      },
      immediate: true
    }
  },
  methods: {
    isEmpty,
    addRowspanStyle(htmlStr) {
      const regex = /<th(\s+[^>]*?rowspan=["'](\d+)["'][^>]*)>/gi;
      return htmlStr.replace(regex, (match, attrs, val) => {
        return `<th${attrs} style="--span: ${val}">`;
      });
    }
  }
};
</script>
